from openai import OpenAI

client = OpenAI(api_key="sk-kpwjrfmryqwfqtbehwnihsnnuakzyvowzwusvecvpvwwbadr", base_url="https://api.siliconflow.cn/v1")

# 初始化对话历史
messages = []

while True:
    user_input = input("你: ")  # 获取用户输入
    if user_input.lower() in ["exit", "quit", "q"]:  # 退出条件
        print("对话结束。")
        break

    # 记录用户输入
    messages.append({"role": "user", "content": user_input})

    # 调用 API
    response = client.chat.completions.create(
        model='deepseek-ai/DeepSeek-R1',
        messages=messages,
        stream=True
    )

    # 逐步打印 AI 回复
    reply = ""
    for chunk in response:
        content = chunk.choices[0].delta.content
        if content:
            print(content, end='', flush=True)
            reply += content

    print("\n")  # 换行，格式更清晰

    # 记录 AI 回复
    messages.append({"role": "assistant", "content": reply})
